const multer = require('multer');
const path = require('path');
const { getStoragePath, generateFileName } = require('../utils/fileHelper');

// 配置存储
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    // 根据文件类型选择存储路径
    let fileType = 'image';
    if (file.mimetype.startsWith('video/')) {
      fileType = 'video';
    }
    const uploadPath = path.join(__dirname, '../../', getStoragePath(fileType));
    cb(null, uploadPath);
  },
  filename: function (req, file, cb) {
    cb(null, generateFileName(file.originalname));
  }
});

// 文件类型过滤
const fileFilter = (req, file, cb) => {
  // 允许的文件类型
  const allowedImageTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
  const allowedVideoTypes = ['video/mp4', 'video/webm', 'video/ogg'];
  
  if (allowedImageTypes.includes(file.mimetype) || allowedVideoTypes.includes(file.mimetype)) {
    cb(null, true);
  } else {
    cb(new Error('不支持的文件类型'), false);
  }
};

// 创建上传中间件
const upload = multer({
  storage: storage,
  fileFilter: fileFilter,
  limits: {
    fileSize: 1024 * 1024 * 50 // 限制50MB
  }
});

module.exports = upload; 